package everydayGrade.t4;

import java.util.*;

/**
 * @Author: Siantar
 * @Date: 2023-07-18-14:05
 * @Description: 1.0
 */
public class T0994 {
    int[][] diff = new int[][]{{-1, 0}, {0, -1}, {1, 0}, {0, 1}};

    public int orangesRotting(int[][] grid) {
        int m = grid.length, n = grid[0].length;
        Deque<int[]> deque = new LinkedList<>();
        int sum = 0;
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; j++) {
                if (grid[i][j] == 2) {
                    deque.offerLast(new int[]{i, j});
                } else if (grid[i][j] == 1) {
                    sum++;
                }
            }
        }
        if (sum==0)return 0;
        int ans = -1;
        while (!deque.isEmpty()) {
            int size = deque.size();
            for (int i = 0; i < size; i++) {
                int[] p = deque.pollFirst();
                for (int j = 0; j < 4; j++) {
                    int x = p[0] + diff[j][0], y = p[1] + diff[j][1];
                    if (0 <= x && x < m && 0 <= y && y < n && grid[x][y] == 1) {
                        grid[x][y] = 2;
                        deque.offerLast(new int[]{x, y});
                        sum--;
                    }
                }
            }
            ans++;
        }
        return sum == 0 ? ans : -1;
    }
}
